package com.tech.koufu.ui.activity.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.Volley;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.model.TrackerUser;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.Statics; 
import com.tech.koufu.ui.activity.UserDetailActivity;
import com.tech.koufu.ui.adapter.AttenFansAdapter;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
/**
 * 我的关注，我的粉丝
 * @author jl_luo
 *
 */
public class AttentionFansFragment extends Fragment {
	public static final String TAG = AttentionFansFragment.class.getName();
	private int page = 1;
	private int index = 1;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private AttenFansAdapter mAdapter;
	private Context context;
//	private RequestQueue mQueue; 
	private MyApplication myApp;
//	CookieStringRequest stringRequest;
	BitmapUtils bitmapUtils;
	private ArrayList<TrackerUser> datas;
	private String userid;
	private View rootView;
	
	public static AttentionFansFragment newInstance(int index,String userid) {
		AttentionFansFragment hf = new AttentionFansFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("index", index);
		bundle.putString("userid", userid); 
		hf.setArguments(bundle); 
		return hf;
	}
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
		if (rootView == null) {
			rootView = inflater.inflate(R.layout.lv_list_competition, container, false);   
			myApp = (MyApplication) getActivity().getApplication();
			context = getActivity().getApplicationContext();
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		initView();
		return rootView; 
	}
	private void initView() { 
		mPullToRefreshListView = (PullToRefreshListView) rootView.findViewById(R.id.lv_stocks);
		actualListView = mPullToRefreshListView.getRefreshableView();
		registerForContextMenu(actualListView);
		  bitmapUtils =  new BitmapUtils(context);
		mAdapter = new AttenFansAdapter(context, index, bitmapUtils);
		actualListView.setAdapter(mAdapter);
		actualListView.setOnItemClickListener(itemClick);
	}
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
		super.onActivityCreated(savedInstanceState);
		initData();
	}
	private void initData() { 
		Bundle bundle = getArguments();
		if(bundle!=null){
			userid = bundle.getString("userid"); 
			index = bundle.getInt("index"); 
		}
		datas = new ArrayList<TrackerUser>();
//		mQueue = Volley.newRequestQueue(context);  
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	datas.clear();
		        	page=1; 
		        }else {
		        	page++; 
		        }  
				load();
			}
		});
		mPullToRefreshListView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true));
		mPullToRefreshListView.setRefreshing(true);
		mPullToRefreshListView.setMode(Mode.BOTH);
		mAdapter.sessionID = myApp.phpsessid;
//		mAdapter.mQueue = mQueue;
//		if(userid==null){
//			userid = myApp.getDigitalid();
//		}
		mAdapter.userId = userid;
	}
	private void load(){
		String urlName = "";
		if(index ==1){
			urlName = Statics.IF_myConcern;
		}else{
			urlName = Statics.IF_fans;
		}
		String url = Statics.URL_PHP+urlName; Log.v(TAG, url);
		CookieStringRequest stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try { 
						Log.d(TAG, response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						if(status.equals("0")){
							JSONArray arry = obj.optJSONArray("data");
							if(arry!=null){
								int length = arry.length();
								for(int i=0;i<length;i++){
									JSONObject o = arry.getJSONObject(i);
									if(index==1){
										TrackerUser cg = new TrackerUser(o,3);
										datas.add(cg);
									}else {
										TrackerUser cg = new TrackerUser(o,4);
										datas.add(cg);
									} 
								}
								if(null!=datas && datas.size()>0){
									mAdapter.datas = datas;
									mAdapter.notifyDataSetChanged(); 
								}  
							}else{
								page--;
							}
						}else{  
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				}
				mPullToRefreshListView.onRefreshComplete();
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				mPullToRefreshListView.onRefreshComplete();
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("page", page+"");     
				params.put("userID", userid);//myApp.digitalid userid Statics.test_user_id
				return params;
			}
		}; 
		stringRequest.setTag(TAG);
		stringRequest.setHeader(myApp.phpsessid);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(stringRequest);
	}
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {  
			TrackerUser tu = datas.get(position-1);
			Intent intent = new Intent(getActivity(),UserDetailActivity.class);
			intent.putExtra("userid", tu.trackId);
			intent.putExtra("username", tu.trackName);
			intent.putExtra("groupid", tu.trackGid);
			intent.putExtra("webId", tu.webId);
			startActivity(intent);
		}
	};

	@Override
	public void onPause() { 
		super.onPause();
	}
	@Override
	public void onStop() { 
		super.onStop(); 
		Log.v(TAG, "~~~~onStop~~~~~~");
		RequestQueueSingleton.getInstance(context).cancleAllReq(TAG);  
		if(bitmapUtils!=null){
			bitmapUtils.cancel(); 
		}
//		datas.clear();
	}
	
	 
}
